package com.zhuliwei.rabbitmq.direct.consumer;

import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.templates.EmailTemplate;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.zhuliwei.constants.RabbitConstants.EMAIL_QUEUE1;

/**
 * 邮箱验证码消息消费
 *
 * @author 朱力维
 * @time 2024/11/17 18:11
 **/
@RabbitListener(queues = EMAIL_QUEUE1) //指定监听哪个消息队列
@Component
public class EmailAuthCodeConsumer {
    @Resource
    private JavaMailSender sender;
    @RabbitHandler
    public void emailAuthCodeToUser(Map<String, String> messageMap) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(SystemConstants.EMAIL_SENDER, "小朱");
            helper.setTo(messageMap.get("to"));
            helper.setSubject(SystemConstants.BLOG_SUBJECT);
            // 接收调用方传入的验证码
            String text = EmailTemplate.VALIDATE_CODE_TEMPLATE.replace("$EMAIL$", messageMap.get("to")).replace("$CODE$", messageMap.get("authCode"));
            helper.setText(text, true);
            // 发送填充好的整个html页面
            sender.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SystemException(AppHttpCodeEnum.SYSTEM_ERROR);
        }
    }
}
